package org.god.ibatis.core;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;

import javax.sql.DataSource;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SqlSessionFactoryBuilder {

    public SqlSessionFactoryBuilder() {
    }

    public SqlSessionFactory build(InputStream in ) {
        //解析godbatis-config.xml文件
        SAXReader saxReader = new SAXReader();
        SqlSessionFactory factory = null;
        try {
            Document document = saxReader.read(in);
            Element environments = (Element)document.selectSingleNode("/configuration/environments");
            String defaultId = environments.attributeValue("default");
            Element environment = (Element) document.selectSingleNode("/configuration/environments/environment[@id'" + defaultId + "']");
            Element transacationElt = environment.element("transactionManager");
            Element dataSourceElt = environment.element("dataSource");

            //获取数据源对象
            DataSource dataSource = getDataSource(dataSourceElt);
            //获取事务管理器
            Transaction transaction = getTransaction(transacationElt);
            //获取mappedStatements
            Map<String,MappedStatement> mappedStatements = null;
            //解析完成之后，构建SqlSessionFactory对象。
             factory = new SqlSessionFactory(transaction,mappedStatements);


        } catch (Exception e) {
            e.printStackTrace();
        }

        return factory;





    }

    private Transaction getTransaction(Element transacationElt) {
        return null;
    }

    private DataSource getDataSource(Element dataSourceElt) {
        HashMap<String, String> map = new HashMap<>();

        //获取所有的property
        List<Element> propertyElts = dataSourceElt.elements("property");
        propertyElts.forEach(propertyElt -> {
            String name = propertyElt.attributeValue("name");
            String value = propertyElt.attributeValue("value");
            map.put(name, value);
        });
        String type = dataSourceElt.attributeValue("type").trim().toUpperCase();
        if (Const.UN_POOLED_DATASOURCE.equals(type)) {
            UnPooledDataSource unPooledDataSource = new UnPooledDataSource(map.get("driver"), map.get("url"), map.get("username"), map.get("password"));
        }
        if (Const.POOLED_DATASOURCE.equals(type)) {

            PooledDataSource pooledDataSource = new PooledDataSource();
        }
        if (Const.JNDI_DATASOURCE.equals(type)) {

            JIDNDataSource jidnd = new JIDNDataSource();
        }
        return null;
    }
}
